package apis

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"strings"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	"tuowei.com/pkg/util"
	"tuowei.com/pkg/xlog"
)

type SysQuestionBank struct {
	api.Api
}

// GetPage
// @Summary 题目信息数据
// @Description 获取JSON
// @Tags 题目
// @Param username query string false "username"
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class [get]
// @Security Bearer
func (e SysQuestionBank) GetPage(c *gin.Context) {
	s := service.SysQuestionBank{}
	req := dto.SysQuestionBankGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysQuestionBank, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Insert
// @Summary 创建题目
// @Description 获取JSON
// @Tags 题目
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysCourseInsertReq true "题目数据"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-course [post]
// @Security Bearer
func (e SysQuestionBank) Insert(c *gin.Context) {
	s := service.SysQuestionBank{}
	req := dto.SysQuestionBankInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Insert(&req)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	e.OK(req.GetId(), "创建成功")
}

// Update
// @Summary 修改题目数据
// @Description 获取JSON
// @Tags 题目
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysUserUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{classId} [put]
// @Security Bearer
func (e SysQuestionBank) Update(c *gin.Context) {
	s := service.SysQuestionBank{}
	req := dto.SysQuestionBankUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Update(&req)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete
// @Summary 删除题目数据
// @Description 删除数据
// @Tags 题目
// @Param userId path int true "classId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{classId} [delete]
// @Security Bearer
func (e SysQuestionBank) Delete(c *gin.Context) {
	s := service.SysQuestionBank{}
	req := dto.SysQuestionBankById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// 设置删除人
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))

	// 数据权限检查
	p := actions.GetPermissionFromContext(c)
	var list []*models.SysQuestionBankLink

	err = e.Orm.Debug().Find(&list).Error
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	maps := make([]string, 0)
	for _, vs := range list {
		maps = append(maps, strings.Split(vs.QuestionBankStr, ",")...)
	}

	ints := req.GetId()
	ss := ints.([]int)
	xlog.Pretty(ss)
	if util.IsInArray(strconv.Itoa(ss[0]), maps) {
		e.Error(500, errors.New("题目已存在练习题中,请勿删除！"), "题目已存在练习题中,请勿删除！")
		return
	}
	err = s.Remove(&req, p)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "删除成功")
}

func (e SysQuestionBank) Get(c *gin.Context) {
	s := service.SysQuestionBank{}
	req := dto.SysQuestionBankById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var object models.SysQuestionBank
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &object)
	if err != nil {
		e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return
	}

	e.OK(object, "查询成功")
}

func (e SysQuestionBank) SaveSelectedQuestionBank(c *gin.Context) {
	s := service.SysQuestionBank{}
	req := dto.SaveSelectedQuestionBankReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = s.SaveSelectedQuestionBank(&req)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "成功")
	return
}

func (e SysQuestionBank) GetQuestionBankList(c *gin.Context) {
	s := service.SysQuestionBank{}
	req := dto.SysQuestionBankListByIDS{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	list, err := s.GetQuestionBankList(&req)
	if err != nil {
		if strings.EqualFold(err.Error(), gorm.ErrRecordNotFound.Error()) {
			e.OK(list, "无数据")
			return
		}
		e.Error(500, err, err.Error())
		return
	}
	e.OK(list, "成功")
	return
}

func (e SysQuestionBank) Save(c *gin.Context) {
	s := service.SysExercises{}
	req := dto.SaveChapterSubmitReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	list := make([]models.SysQuestionBankLink, 0)
	err = s.Mul(&req, &list)
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	strArr := make([]string, 0)
	for _, v := range list {
		arr := strings.Split(v.QuestionBankStr, ",")
		strArr = append(strArr, arr...)
	}

	if req.LinkType == 1 {

	} else if req.LinkType == 2 {
		var model models.SysExercises
		e.Orm.Debug().Model(model).Where("id = ?", req.ObjId).UpdateColumn("count", len(strArr))
	} else if req.LinkType == 3 {
		var model models.SysExamination
		e.Orm.Debug().Model(model).Where("id = ?", req.ObjId).UpdateColumn("count", len(strArr))
	}

	e.OK(nil, "保存成功")
	return
}
